package com.foreveross.proxyip.local;

import java.io.Serializable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.foreveross.proxyip.IProxyIpProvider;
import com.foreveross.proxyip.ProxyIpModel;
/**
 * 本地的简单池方式提供代理ip
 * @author Administrator
 *
 */
@Component("localProxyIpProvider")
public class LocalProxyIpProvider implements IProxyIpProvider {
	
	public Logger logger = LoggerFactory.getLogger(LocalProxyIpProvider.class);
	/**
	 * 这种方式在并发量大时，也会有问题
	 */
	@Override
	public synchronized ProxyIpModel provideProxyIp() {
		ProxyIpSimplePool pool = ProxyIpPoolsManager.getInstanceManager().getDefaultSimplePool();
		ProxyIpModel model = pool.getProxyIp();
		if(logger.isInfoEnabled()){
			logger.info(String.format("获取到的代理ip:%s", model.getIp()+":"+model.getPort()));
		}
		return model;
	}


	@Override
	public synchronized void rollBackProxyIp(ProxyIpModel model) {
		if(model == null || model.getHasRecycle()) return;
		model.setHasRecycle(true);//标识已回收过了
			long stime = System.currentTimeMillis();
			logger.info(String.format("回收代理ip=%s(状态：%s), 耗时=%sms", model.getIp(), model.getUseStatus(), System.currentTimeMillis()-stime));
			//如果失败了，则从池中丢弃
			if(model.getUseStatus() == ProxyIpModel.UNENBLE){
				ProxyIpSimplePool pool = ProxyIpPoolsManager.getInstanceManager().getDefaultSimplePool();
				pool.removeProxyIp(model);
			}
	}
	@Override
	public synchronized ProxyIpModel provideProxyIp(Serializable channelId) {
		return provideProxyIp();
	}


	@Override
	public List<ProxyIpModel> provideProxyIps() {
		logger.error("本地池不支持多代理IP提供");
		return null;
	}


	@Override
	public List<ProxyIpModel> provideProxyIps(Serializable channelId) {
		logger.error("本地池不支持多代理IP提供");
		return null;
	}

}
